package global

import (
	"os"

	"errors"
	"log"

	"gopkg.in/pg.v5"
)

var DB *pg.DB

func OpenDB() error {
	if DB != nil {
		return nil
	}
	addr := Config.Section("database").Key("addr").String()
	user := Config.Section("database").Key("user").String()
	pwd := Config.Section("database").Key("pwd").String()
	name := Config.Section("database").Key("name").String()
	logOutput := Config.Section("database").Key("logOutput").String()
	logFile := Config.Section("database").Key("logFile").String()
	if addr == "" {
		return errors.New("配置文件[database]节点的addr参数不正确")
	}
	if user == "" {
		return errors.New("配置文件[database]节点的user参数不正确")
	}
	if pwd == "" {
		return errors.New("配置文件[database]节点的pwd参数不正确")
	}
	if name == "" {
		return errors.New("配置文件[database]节点的name参数不正确")
	}
	DB = pg.Connect(&pg.Options{
		Addr:     addr,
		User:     user,
		Password: pwd,
		Database: name,
	})
	var dbLogger *log.Logger
	switch logOutput {
	case "console":
		dbLogger = log.New(os.Stdout, logFile, log.LstdFlags)
		pg.SetQueryLogger(dbLogger)
	case "file":
		f, err := os.Create(logFile)
		if err != nil {
			return err
		}
		dbLogger = log.New(f, logFile, log.LstdFlags)
		pg.SetQueryLogger(dbLogger)
	}
	return nil
}
